#include "Utils.h"
#include "MonkeyRuntime.h"
#include "PhidgetRootObject.h"
#include "MonkeySystemObject.h"
#include "PhidgetManager.h"


extern PhidgetManager *gPhidgetManager;


//
// Add the number of milliseconds to the given timeval struct.
//
void timeval_addms(struct timeval *tp, long ms)
{
	tp->tv_sec += (ms / 1000);
	tp->tv_usec += ((ms % 1000) * 1000);
	if (tp->tv_usec > 1000000)
	{
		tp->tv_sec += (tp->tv_usec / 1000000);
		tp->tv_usec %= 1000000;
	}
}


//
// Subtract the number of milliseconds from the given timeval struct.
//
void timeval_subms(struct timeval *tp, long ms)
{
	tp->tv_sec -= (ms / 1000);
	tp->tv_usec -= ((ms % 1000) * 1000);
	if (tp->tv_usec < 0)
	{
		tp->tv_sec += (tp->tv_usec / 1000000); /* add a negative number */
		tp->tv_usec %= 1000000;
		tp->tv_usec += 1000000; /* if tv_sec = -800, final value should be 999200 */
	}
}


//
// Subtract the second timeval from the first timeval and return the result in
// milliseconds.
//
long timeval_diffms(struct timeval *tp1, struct timeval *tp2)
{
	long ms;


	ms = ((tp1->tv_sec - tp2->tv_sec) * 1000);
	ms += ((tp1->tv_usec - tp2->tv_usec) / 1000);
	
	return ms;
}


//
// Create a new "standard" monkey context that can be used for running scripts.
//
MonkeyContext *CreateStandardMonkeyContext()
{
    MonkeyRuntime *rt = MonkeyRuntime::SharedRuntime();
    MonkeyContext *ctx = rt->CreateContext();
    PhidgetRootObject *obj = new PhidgetRootObject(gPhidgetManager, rt);
    MonkeySystemObject *sys = new MonkeySystemObject();


	ctx->AddObject(obj);
	ctx->AddObject(sys);

    return ctx;
}

